package com.app.controller;

import com.app.model.*;
import com.app.service.*;
import com.app.util.CommonHelp;
import com.app.util.Result;
import com.app.util.TokenUtils;
import com.app.vo.CategoryVo;
import com.app.vo.MessageVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
@Controller
@RequestMapping("/api/message")
public class MessageController {
    @Autowired
    private AdminUserService adminUserService;
    @Autowired
    private TypeService typeService;
    @Autowired
    private PersonService personService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private MessageReadService messageReadService;
    @Autowired
    private MessageService messageService;

    //消息类型查询
    @GetMapping("/getMessageTypeList")
    public Result<Object> getMessageTypeList(HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        CategoryVo vo = new CategoryVo();
        List<CategoryModel> categoryMessageList = categoryService.getCategoryByPid(118);
        vo.setTypeList(categoryMessageList);
        List<Integer> idList = departmentService.getDepId(user.getDepartmentId());
        List<PersonModel> personList = personService.otherPersonList(idList);
        if (personList != null && personList.size() > 0) {
            vo.setPersonList(personList);
        }
        return Result.success(vo);
    }

    @GetMapping("/getMessageList")//消息分页查询
    public Result<Object> getTypeList(
            @RequestParam("page") Integer page,
            @RequestParam("limit") Integer limit,
            @RequestParam("title") String title,
            Integer sortType,
            HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        MessageVo vo = new MessageVo();
        List<MessageModel> modelList = messageService.selectMessageList(page, limit, title,sortType);
        List<CategoryModel> categoryMessageList = categoryService.getCategoryByPid(118);
        if (user.getRoles() == 1) {
            for (int i = 0; i < modelList.size(); i++) {
                for (int i1 = 0; i1 < categoryMessageList.size(); i1++) {
                    if (modelList.get(i).getCategoryId().equals(categoryMessageList.get(i1).getId())) {
                        modelList.get(i).setCategoryText(categoryMessageList.get(i1).getName());
                        if (user.getDepartmentId() == 1) {
                            if (messageReadService.getReadByReadId(modelList.get(i).getId(), user.getDepartmentId()) != null) {
                                modelList.get(i).setIsRead(true);
                                modelList.get(i).setIsReadText("已读");
                            } else {
                                modelList.get(i).setIsRead(false);
                                modelList.get(i).setIsReadText("未读");
                            }
                        } else {
                            if (messageReadService.getReadByReadId(modelList.get(i).getId(), user.getPersonId()) != null) {
                                modelList.get(i).setIsRead(true);
                                modelList.get(i).setIsReadText("已读");
                            } else {
                                modelList.get(i).setIsRead(false);
                                modelList.get(i).setIsReadText("未读");
                            }
                        }
                    }
                }
            }
            int count = messageService.count();
            vo.setCount(count);
            vo.setList(modelList);
            return Result.success(vo);
        }
        if (user.getRoles() == 2) {//二级单位
            List<MessageModel> messageModels = new ArrayList<>();
            for (int i = 0; i < modelList.size(); i++) {
                String[] split;
                if (modelList.get(i).getDepartmentId() != null) {
                    split = modelList.get(i).getDepartmentId().split(",");
                    if (Arrays.asList(split).contains(user.getDepartmentId().toString())) {
                        messageModels.add(modelList.get(i));
                    }
                }
            }
            for (int i = 0; i < modelList.size(); i++) {
                String[] split;
                if (modelList.get(i).getPersonId() != null) {
                    split = modelList.get(i).getPersonId().split(",");
                    if (Arrays.asList(split).contains(user.getPersonId().toString())) {
                        messageModels.add(modelList.get(i));
                    }
                }
            }
            for (int i = 0; i < messageModels.size(); i++) {
                for (int i1 = 0; i1 < categoryMessageList.size(); i1++) {
                    if (messageModels.get(i).getCategoryId().equals(categoryMessageList.get(i1).getId())) {
                        messageModels.get(i).setCategoryText(categoryMessageList.get(i1).getName());
                        if (user.getDepartmentId() == 1) {
                            if (messageReadService.getReadByReadId(messageModels.get(i).getId(), user.getDepartmentId()) != null) {
                                messageModels.get(i).setIsRead(true);
                                messageModels.get(i).setIsReadText("已读");
                            } else {
                                messageModels.get(i).setIsRead(false);
                                messageModels.get(i).setIsReadText("未读");
                            }
                        } else {
                            if (messageReadService.getReadByReadId(messageModels.get(i).getId(), user.getPersonId()) != null) {
                                messageModels.get(i).setIsRead(true);
                                messageModels.get(i).setIsReadText("已读");
                            } else {
                                messageModels.get(i).setIsRead(false);
                                messageModels.get(i).setIsReadText("未读");
                            }
                        }
                    }
                }
            }
        /*    //生序排序
            messageModels.sort(new Comparator<MessageModel>() {
                @Override
                public int compare(MessageModel s1, MessageModel s2) {
                    return s1.getNumber().compareTo(s2.getNumber());
                }
            });
            //降序排列
            messageModels.sort(new Comparator<MessageModel>() {
                @Override
                public int compare(MessageModel s1, MessageModel s2) {
                    return s2.getId().compareTo(s1.getId());
                }
            });*/
            vo.setList(messageModels);
            vo.setCount(messageModels.size());
            return Result.success(vo);
        } else if (user.getRoles() != null) {//战士
            List<MessageModel> messageModels = new ArrayList<>();
            for (int i = 0; i < modelList.size(); i++) {
                String[] split;
                if (modelList.get(i).getPersonId() != null) {
                    split = modelList.get(i).getPersonId().split(",");
                    if (Arrays.asList(split).contains(user.getPersonId().toString())) {
                        messageModels.add(modelList.get(i));
                    }
                }
            }
            for (int i = 0; i < messageModels.size(); i++) {
                for (int i1 = 0; i1 < categoryMessageList.size(); i1++) {
                    if (messageModels.get(i).getCategoryId().equals(categoryMessageList.get(i1).getId())) {
                        messageModels.get(i).setCategoryText(categoryMessageList.get(i1).getName());
                        if (user.getDepartmentId() == 1) {
                            if (messageReadService.getReadByReadId(messageModels.get(i).getId(), user.getDepartmentId()) != null) {
                                messageModels.get(i).setIsRead(true);
                                messageModels.get(i).setIsReadText("已读");
                            } else {
                                messageModels.get(i).setIsRead(false);
                                messageModels.get(i).setIsReadText("未读");
                            }
                        } else {
                            if (messageReadService.getReadByReadId(messageModels.get(i).getId(), user.getPersonId()) != null) {
                                messageModels.get(i).setIsRead(true);
                                messageModels.get(i).setIsReadText("已读");
                            } else {
                                messageModels.get(i).setIsRead(false);
                                messageModels.get(i).setIsReadText("未读");
                            }
                        }
                    }
                }
            }
         /*   messageModels.sort(new Comparator<MessageModel>() {
                @Override
                public int compare(MessageModel s1, MessageModel s2) {
                    return s2.getId().compareTo(s1.getId());
                }
            });*/
            vo.setList(messageModels);
            vo.setCount(messageModels.size());
            return Result.success(vo);
        }
        return null;
    }

    //新增消息
    @PostMapping("/insertMessage")
    public Result<Object> insertMessage(@RequestBody MessageModel messageModel) {
        if (messageModel.getId() > 0) {
            MessageModel mesByMesId = messageService.getMesByMesId(messageModel.getId());
            mesByMesId.setId(0);
            mesByMesId.setPersonId(messageModel.getPersonId());
            messageModel.setCreateTime(CommonHelp.getNowTimestamp());
            messageService.insert(mesByMesId);
            return Result.success("操作成功");
        }
        messageModel.setCreateTime(CommonHelp.getNowTimestamp());
        messageService.insert(messageModel);
        return Result.success("操作成功");
    }

    //删除消息
    @GetMapping("/deleteMessage")
    public Result<Object> deleteMessage(Integer id) {
        messageService.delete(id);
        messageReadService.deleteByMsId(id);
        return Result.success("操作成功");
    }


    @GetMapping("/updateRead")
    public Result<Object> updateRead(Integer id, HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        messageReadService.deleteByMsIdAndPersonId(id,user.getPersonId());
        return Result.success("操作成功");
    }
}
